package com.newland.zxy.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author : zhangxuyuan
 * @Project: springcloudoauth2
 * @Package com.newland.zxy.config
 * @date Date : 2021年02月05日 13:35
 *
 *
 * Oauth2  和  SpringSecurity相关配置
 */

@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    String key="imzxy";

    @Autowired
    private MyTokenConverter myTokenConverter;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("test");

//        RemoteTokenServices services=new RemoteTokenServices();
//        services.setClientId("testClient");
//        services.setClientSecret("111");
//        services.setCheckTokenEndpointUrl("http://127.0.0.1:8901/oauth/check_token");
//        resources.tokenServices(services);


        resources.tokenStore(new JwtTokenStore(converter())).stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .authorizeRequests()
                .antMatchers("/test/**").authenticated()
                .anyRequest().permitAll();
    }


    public JwtAccessTokenConverter converter()
    {
        JwtAccessTokenConverter tokenConverter=new JwtAccessTokenConverter();
        tokenConverter.setVerifier(new MacSigner(key));
        tokenConverter.setSigningKey(key);
        tokenConverter.setAccessTokenConverter(myTokenConverter);
        return tokenConverter;
    }
}
